package cn.wolfcoe.luowowo.common.util.baiducheck;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.auth.DevAuth;
import com.baidu.aip.http.AipHttpClient;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.http.AipResponse;
import com.baidu.aip.util.AipClientConfiguration;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SensitiveWordsUtil {

    public static Map <String, Object> getSensitiveWords(Object content) throws URISyntaxException {
        AipClientConfiguration ss = new AipClientConfiguration();
        JSONObject dd = DevAuth.oauth( "wPlXU2fKZFp4C2Buu5GzGvje", "wAYyK8bFy5WBxrFEcZyiGDGDv3NqPElK", ss );
        System.out.println( dd );
        String access_token = null;
        try {
            access_token = (String) dd.get( "access_token" );
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AipRequest request = new AipRequest();
        request.setUri( new URI( "https://aip.baidubce.com/rest/2.0/antispam/v2/spam" ) );
        request.addBody( "access_token", access_token );
        request.addBody( "content", content );
        AipResponse post = AipHttpClient.post( request );
        String bodyStr = post.getBodyStr();
        System.out.println( bodyStr );
        CheckTextResult result = JSON.parseObject( bodyStr, CheckTextResult.class );
        HashMap <String, Object> map = new HashMap <>();
        //spam返回true表示有敏感词
        boolean spam = "1".equals( result.getResult().getSpam() );
        map.put( "spam", spam );
        if (!spam) {
            map.put( "list", null );
        }
        List <Reject> reject = result.getResult().getReject();
        List list = new ArrayList();
        for (Reject rm : reject) {
            List hit = rm.getHit();
            if (hit != null && hit.size() > 0) {
                list.addAll( hit );
            }
        }
        map.put( "list", list );
        return map;
    }

    public static CheckResultVo SensitiveWordCheck(String str) {
        List <String> list = new ArrayList <>(  );
        Map <String, Object> map=new HashMap <>(  );
        boolean spam=true;
        try {
            map= SensitiveWordsUtil.getSensitiveWords( str );
            spam = (Boolean) map.get( "spam" );
             list =( List <String>) map.get( "list" );
        }catch (Exception e){
            e.printStackTrace();
        }
        //如果有敏感词,就替换,没有敏感词不执行
        if ( spam && list .size() > 0) {
            for (String word : list) {
                String temp = "";
                for (int i = 1; i <= list.size(); i++) {
                    temp = temp + "*";
                }
                str = str.replaceAll( word, temp );
            }
        }
        return new CheckResultVo(spam,str);
    }

}
